﻿using Microsoft.Extensions.Logging;
using Spring.Util;
using Sys.Expressions;
using Sys.Workflow.Bpmn.Models;
using Sys.Workflow.Engine.Delegate;
using Sys.Workflow.Engine.Impl.Cfg;
using Sys.Workflow.Engine.Impl.EL;
using Sys.Workflow.Engine.Impl.Persistence.Entity;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionManager = Sys.Workflow.Engine.Impl.EL.ExpressionManager;

namespace Sys.Workflow.Engine.impl.util
{
    public class IOParameterUtil
    {

        private static readonly ILogger<IOParameterUtil> LOGGER = ProcessEngineServiceProvider.LoggerService<IOParameterUtil>();

        public static void ProcessInParameters(CallActivity callActivity, IExecutionEntity parentExecution, ConcurrentDictionary<string, object> variables, ExpressionManager expressionManager)
        {
            if (callActivity.InParameters != null)
            {
                foreach (var parameter in callActivity.InParameters)
                {
                    if (parameter == null)
                        continue;

                    var source = parameter.Source;
                    var target = parameter.Target;

                    if (string.IsNullOrEmpty(target))
                        continue;

                    object value = null;

                    if (!string.IsNullOrEmpty(source))
                    {
                        // 支持表达式
                        if (source.StartsWith("${") || source.StartsWith("#{"))
                        {
                            value = expressionManager.CreateExpression(source).GetValue(parentExecution);
                        }
                        else if (parentExecution.Variables != null && parentExecution.Variables.ContainsKey(source))
                        {
                            value = parentExecution.Variables[source];
                        }
                        else
                        {
                            value = source;
                        }
                    }

                    variables.TryAdd(target, value);
                }
            }
        }
    }
}
